const service = require("../../../service/port.js");
const activityService = require("../../../service/activity")
const rules = require("../../../utils/util.js");
import Toast from "../../../miniprogram_npm/@vant/weapp/toast/toast.js";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    memberInfo : {},
    isPaying: false,
    postageMoney: 0,
    remark: "",
    checked: true,
    isOnLine: true, //是否线上
    showbtn: true,
    showaddbtn: true,
    productInfo: {}, //详情
    orderdetailList: [],
    isActivity: false,
    currentAddress: {
      receiptName: '***',
      receiptMobile: '***',
      provinceName: '***',
      cityName: '***',
      areaName: '***',
      receiptAddress: '***'
    },
    currentStore: {},
    storeList: [],
    diamondNum: 0, //拥有总钻石
    deductionMoney: 0, //可兑换钱数(元)
    deductionDiamond: 0, //sku抵扣钻石数
    ownSpec: "",
    totalMoney: '', //总金额
    oldMoney: 0,
    actualPay: 0, //实际付款数（元）
    cancheck: false,
    services: [],
    postList: [],
    showCoupon: false,
    showCouponitem: true,
    couponList: [],
    couponObj: {},
    type: "",
    spuDetail: "",
    spuId: "",
    currentNum: "",
    promotiomIds: "",
    activity: "",

    distributionType: 0, //配送方式
    showtype: false, //配送方式弹出窗
    showtype1: false, //配送方式弹出窗
    showtype2: false, //配送方式弹出窗
    distributionType1: 0, //配送方式
    distributionType2: 0, //配送方式
    showTime: false, //时间段
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    cards: 136, //储值卡扣除
    member: 80, //会员卡扣除
    type1: true, //即时配送或上门取货
    type2: false, //快递物流或上门取货
    type3: false, //快递物流或即时配送
    type4: false, //收货时段
    showstoreList: false, //门店列表
    timelyDelivery: 1,
    timetype: 1, //时间类型
    sendstartTime: "", //收货时段开始时间
    sendendTime: "" //收货时段结束时间
  },

  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },

  computedCardAndMember() {

    let data = {
      id: wx.getStorageSync("userInfo").id
    }

    service.getBalanceByCosId(data, (res) => {
      this.setData({ memberInfo : res.data.Dic})
      if (res.code == '00000') {
        let actualPay;
        if (!this.data.isActivity) {
          actualPay = this.data.oldMoney * res.data.Dic.discount / 100
        } else {
          actualPay = String(Number(this.data.actualPay).toFixed(2))
        }

        let cards = res.data.balance || 0
        let member = res.data.vipMoney || 0

        let dif1Price = actualPay - cards
        let dif2Price = 0
        if (dif1Price < 0) {
          this.setData({
            actualPay: 0,
            cards: actualPay,
            member: 0
          })
        } else {
          dif2Price = dif1Price - member
          if (dif2Price < 0) {
            this.setData({
              actualPay: 0,
              cards: cards.toFixed(2),
              member: dif1Price.toFixed(2)
            })
          } else {
            this.setData({
              actualPay: dif2Price.toFixed(2),
              cards: cards.toFixed(2),
              member: member.toFixed(2)
            })
          }
        }
      }
    })
  },

  chooseTime(e) {
    if (this.data.timetype == 1) {
      this.setData({
        sendstartTime: rules.formatTime2(new Date(e.detail)),
        showTime: false
      })
    } else {
      this.setData({
        sendendTime: rules.formatTime2(new Date(e.detail)),
        showTime: false
      })
    }

  },
  onClose() {
    this.setData({
      show: false,
      showtype: false,
      showtype1: false,
      showTime: false,
      showstoreList: false
    });
  },
  showtypePop(e) {
    //console.log(e.currentTarget.dataset)
    if (e.currentTarget.dataset.index == "1") {
      this.setData({
        showtype: true
      })
    } else if (e.currentTarget.dataset.index == "2") {
      this.setData({
        showtype1: true
      })
    } else if (e.currentTarget.dataset.index == "3") {
      this.setData({
        showtype2: true
      })
    } else if (e.currentTarget.dataset.index == "4") {
      this.setData({
        showTime: true,
        timetype: 1
      })
    } else {
      this.setData({
        showTime: true,
        timetype: 2
      })
    }

  },
  onChange1(event) {
    this.setData({
      distributionType: event.detail,
    });
  },
  onClick1(event) {
    const {
      name,
      index
    } = event.currentTarget.dataset;
    if (index == 1) {
      this.setData({
        distributionType: name,
      });
    } else if (index == 2) {
      this.setData({
        distributionType1: name,
      });
    } else {
      this.setData({
        distributionType2: name,
      });
    }

  },
  onChange2(event) {
    this.setData({
      distributionType1: event.detail,
    });
  },
  onChange3(event) {
    this.setData({
      distributionType2: event.detail,
    });
  },
  chooseDistributionType(e) {
    this.setData({
      showtype: false,
      showtype1: false,
      showtype2: false
    })
    if (e.currentTarget.dataset.type == '1') {
      if (this.data.distributionType == '1') {
        this.setData({
          type1: false,
          type2: true,
          type3: false,
          type4: true,
          isOnLine: true,
          timelyDelivery: 2
        })
        this.changeIsOnLineStatus()
      } else {
        this.setData({
          type1: false,
          type2: false,
          type3: true,
          type4: true,
          isOnLine: false,
          timelyDelivery: 3
        })
      }
    } else if (e.currentTarget.dataset.type == '2') {
      if (this.data.distributionType1 == '1') {
        this.setData({
          type1: true,
          type2: false,
          type3: false,
          type4: false,
          isOnLine: true,
          timelyDelivery: 1
        })
        this.changeIsOnLineStatus()
      } else {
        this.setData({
          type1: false,
          type2: false,
          type3: true,
          type4: true,
          isOnLine: false,
          timelyDelivery: 3
        })
      }
    } else {
      if (this.data.distributionType2 == '1') {
        this.setData({
          type1: true,
          type2: false,
          type3: false,
          type4: false,
          isOnLine: true,
          timelyDelivery: 1
        })
        this.changeIsOnLineStatus()
      } else {
        this.setData({
          type1: false,
          type2: true,
          type3: false,
          type4: true,
          isOnLine: true,
          timelyDelivery: 2
        })
        this.changeIsOnLineStatus()
      }
    }
  },
  getStore(e) {
    //console.log(e)
    this.setData({
      showstoreList: false,
      showbtn: false,
      currentStore: e.detail
    })
  },
  changeIsOnLineStatus() {
    // this.setData({
    //   isOnLine: !this.data.isOnLine,
    // });
    if (!this.data.isOnLine) {
      this.setData({
        currentAddress: {},
        postageMoney: 0
      });
    } else {
      this.setData({
        currentStore: {},
      });
      service.getdefaultAddress(wx.getStorageSync("userInfo").id, (res) => {
        //console.log(res);
        this.setData({
          currentAddress: res.data[0] || {},
          showaddbtn: res.data[0] ? false : true,
        });
        if (res.data[0]) {
          this.getCarriage(res.data[0].provinceId)
        }
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.computedCardAndMember()
    let accountInfo = options.accountInfo
    if (accountInfo) {
      var productInfo = JSON.parse(options.accountInfo);
      this.setData({
        activity: "",
        promotiomIds: productInfo.shoppingList[0].setmealId ? productInfo.shoppingList[0].setmealId : ""
      })
      let tempList = [];
      if (productInfo.isfixedprice) {
        this.setData({
          showCouponitem: false,
          activity: 3,
        })
      };
      if (productInfo.isActivity) {
        productInfo.shoppingList.forEach(item => {
          tempList.push({
            companyName: null,
            createTime: null,
            customerId: null,
            id: null,
            image: item.skuImage || '',
            modifyTime: null,
            num: 1,
            ownSpec: item.skuTitle || '',
            price: String(item.skuPrice) || '',
            priceFen: String(item.skuPrice / 100) || '',
            productType: "0",
            setmealId: item.setmealId,
            setmealMoney: item.setmealMoney,
            setmealName: item.setmealName,
            skuId: item.skuId || '',
            spuId: item.spuId || '',
            title: item.skuTitle || '',
            url: null,
            useDiamond: null,
          })
        })
      } else {
        tempList = productInfo.shoppingList
      }
      this.setData({
        orderdetailList: tempList,
        isActivity: productInfo.isActivity || false,
        totalMoney: parseFloat(productInfo.totalMoney).toFixed(2),
        oldMoney: parseFloat(productInfo.totalMoney).toFixed(2),
        actualPay: (parseFloat(productInfo.totalMoney) + parseFloat(this.data.postageMoney)).toFixed(2),
      });
    }
  },

  getCouponList() {

    let orderList = this.data.orderdetailList
    let spuIds = [];
    orderList.forEach(item => {
      if (item.productType == 0) spuIds.push(item.spuId)
    })
    spuIds = spuIds.join(',')
    let cutomerId = wx.getStorageSync("userInfo").id
    activityService.getCommodityCoupon({
      spuIds,
      cutomerId
    }, (res) => {
      if (res.data.length > 0) {
        this.setData({
          showCoupon: true,
          couponList: res.data
        })

      }
    })
  },
  handleReduce(e) {
    let item = e.currentTarget.dataset.data
    this.setData({
      couponObj: item,
      showCoupon: false
    })

    let orderList = this.data.orderdetailList
    for (let i = 0; i < orderList.length; i++) {
      let goodsItem = orderList[i]
      if (goodsItem.spuId == item.spuId) {

        let totalMoney = parseFloat(goodsItem.priceFen) * goodsItem.num
        let discountMoney = this.data.totalMoney * this.data.memberInfo.discount / 100
        //满减
        if (totalMoney >= item.satifyMoney) {
          this.setData({
            actualPay: parseFloat((discountMoney - item.reduceMoney).toFixed(2)) + parseFloat(this.data.postageMoney)
          })
          break;
        }

      }
    }
  },
  handleDiscount(e) {
    let item = e.currentTarget.dataset.data
    this.setData({
      couponObj: item,
      showCoupon: false
    })
    let orderList = this.data.orderdetailList
    let isDiscount = false
    let totalMoney = 0
    for (let i = 0; i < orderList.length; i++) {
      let goodsItem = orderList[i]
      console.log(1111, goodsItem)
      if (goodsItem.spuId == item.spuId && !isDiscount) {
        isDiscount = true
        totalMoney += Number(goodsItem.price) * goodsItem.num * item.dicounts / 10
      } else {
        totalMoney += Number(goodsItem.price) * goodsItem.num
      }
    }
    let actualPay = Number((totalMoney / 100).toFixed(2)) + Number(this.data.postageMoney)
    this.setData({
      actualPay: actualPay
    })
  },
  onClose() {
    this.setData({
      showCoupon: false
    })
  },
  goToMyAddress() {
    wx.setStorageSync("isconfirmorder", true);
    wx.navigateTo({
      url: "/pages/mine/address/index",
    });
  },

  goToSelectStore() {
    this.setData({
      showstoreList: true
    })
    // wx.navigateTo({
    //   url: "/pages/order/outlineserivce/index",
    // });
  },

  blurEvent(e) {
    this.setData({
      remark: e.detail.value,
    });
  },

  computedFreight() {
    if (!this.data.currentAddress.id) {
      return;
    }
    let scList = [] //商城数组
    let smList = [] //商盟数组
    let orderdetailList = this.data.orderdetailList
    orderdetailList.forEach(item => {
      if (item.productType == 0) scList.push(item)
      else smList.push(item)
    })

    let freight = 0
    this.scOrder(scList, null, (money1) => {

      freight += money1
      this.setData({
        postageMoney: freight
      })

      this.smOrder(smList, null, (money2) => {

        freight += money2
        console.log(1111, freight / 100)
        let totalMoney = this.data.totalMoney
        let actualPay = parseFloat(totalMoney) + (freight / 100)

        this.setData({
          actualPay: parseFloat(actualPay).toFixed(2),
          postageMoney: freight / 100
        })

        this.computedCardAndMember()
      })
    })

  },

  paynow() {

    if (this.data.isOnLine) {
      if (!this.data.currentAddress.id) {
        Toast.fail("请选择地址");
        return;
      }
    } else {
      if (!this.data.currentStore.storeName) {
        Toast.fail("请选择门店");
        return;
      }
    }


    let isPaying = this.data.isPaying
    if (isPaying) return
    this.setData({ isPaying: true })
    let scList = [] //商城数组
    let smList = [] //商盟数组
    let orderdetailList = this.data.orderdetailList
    orderdetailList.forEach(item => {
      if (item.productType == 0) scList.push(item)
      else smList.push(item)
    })
    let paramList = []
    wx.showLoading({
      title: '加载中',
    })
    this.scOrder(scList, (sc) => {
      if (sc) paramList.push(sc)
      this.smOrder(smList, (array) => {
        if (array) paramList = paramList.concat(array)
        this.toPay(paramList, (res) => {
          console.log(11111, res.data.actualPay)
          service.payment({
            id: res.data.id,
            orderNum: res.data.orderNum, //订单编号
            actualPay: res.data.actualPay, //res.data.actualPay//实付金额。单位:分。如:20007，表示:200元7分
            title: "商品描述",
            openid: wx.getStorageSync("userInfo").openId,
            customerId: wx.getStorageSync("userInfo").id, //客户id
          },
            (res1) => {

              if (this.data.actualPay == 0) {
                wx.redirectTo({
                  url: '/pages/paySuccess/index',
                })
              }
              wx.hideLoading();
              // if(res1.data.return_code=='SUCCESS'&&res1.data.result_code=='SUCCESS'){
              if (res1.code == "00000" && res1.data == null) {
                Toast.success("支付成功");
                wx.navigateTo({
                  url: '/pages/paySuccess/index',
                })
              } else {
                wx.requestPayment({
                  appId: res1.data.appId,
                  timeStamp: res1.data.timeStamp,
                  nonceStr: res1.data.nonceStr,
                  package: res1.data.package,
                  signType: res1.data.signType,
                  paySign: res1.data.sign,
                  success(result) {
                    Toast.success("支付成功");
                    wx.navigateBack({
                      delta: 1
                    })
                    this.setData({ isPaying: false })
                  },
                  fail(result) {
                    this.setData({ isPaying: false })
                    Toast.fail("支付失败");
                    wx.redirectTo({
                      url: '/pages/mine/order/unpayList/index'
                    })
                  },
                });
              }
            }
          );
        })

      })
    })

  },
  scOrder(list, callback, freightCb) {
    let param = {
      "totalPay": 0, //总金额，单位为分
      "actualPay": 0, //实付金额。单位:分。如:20007，表示:200元7分
      wechatPay: 0, //微信支付
      memberPay: 0, //会员卡支付
      stordsPay: 0, //储蓄卡支付
      "freightMoney": 0, //运费金额
      "paymentType": "1", //支付类型，1、在线支付，2、货到付款
      "postFee": "0", //邮费。单位:分。如:20007，表示:200元7分
      "customerId": wx.getStorageSync("userInfo").id, //客户id
      "buyerNick": wx.getStorageSync("userInfo").wechatNick, //买家昵称
      "buyerMessage": this.data.remark, //买家留言
      "receiverState": this.data.currentAddress.provinceName || "", //收获地址（省）
      "receiverCity": this.data.currentAddress.cityName || "", //收获地址（市）
      "receiverDistrict": this.data.currentAddress.areaName || "", //收获地址（区/县
      "receiverAddress": this.data.currentAddress.receiptAddress || "", //收获地址（街道、住址等详细地址）
      "receiverMobile": this.data.currentAddress.receiptMobile, //收货人手机
      "receiverZip": "", //收货人邮编
      "receiver": this.data.currentAddress.receiptName, //收货人name
      "invoiceType": "0", //发票类型(0无发票1普通发票，2电子发票，3增值税发票)
      "sourceType": "1", //订单来源：1:微信端 
      "isOffline": "0", //是否为线下 0否 1是
      "storeId": "", //线下门店标识
      "orderdetailList": [],
      "orderType": '',
      "companyName": '',
      "url": '',
      "activity": this.data.activity, //1秒杀活动，2拼团活动3.打包
      "promotionIds": this.data.promotiomIds, //活动标识 秒杀活动 拼团活动的ID
      "timelyDelivery": this.data.timelyDelivery,
      "sendstartTime": this.data.sendstartTime,
      "sendendTime": this.data.sendendTime,
      "storeId": this.data.currentStore.storeId
    }
    if (list.length == 0) {
      freightCb && freightCb(0)
      callback && callback(null);
      return;
    }
    let isYouHui = false

    param.memberPay = this.data.member * 100
    param.stordsPay = this.data.cards * 100
    param.wechatPay = this.data.actualPay *100

    list.length > 0 && this.getCarriage(list, (money) => {
      freightCb && freightCb(money);
      let couponObj = this.data.couponObj
      list.forEach(item => {
        if (couponObj.spuId == item.spuId && !isYouHui) {
          param.totalPay += item.price * item.num
          if (couponObj.type == '满减优惠券') {
            let totalM = item.price * item.num
            if (totalM >= couponObj.satifyMoney) {
              param.actualPay += totalM - couponObj.reduceMoney * 100
            } else {
              param.actualPay += totalM
            }

          } else if (couponObj.type == '折扣优惠券') {
            let money = item.price * item.num * couponObj.dicounts / 10
            param.actualPay += Number(money.toFixed(2))

          }
          isYouHui = true
          param.orderdetailList.push({
            "useCoupons": "1",
            "title": item.title, //商品名称
            "price": item.price, //商品价格
            "num": item.num, //订单商品数量
            "ownSpec": item.ownSpec, //商品规格对象
            "skuId": item.skuId, //详情表中skuId
            "spuId": item.spuId
          })

        } else {
          param.totalPay += item.price * item.num
          param.actualPay += item.price * item.num
          param.orderdetailList.push({
            //couponId: '',
            "title": item.title, //商品名称
            "price": item.price, //商品价格
            "num": item.num, //订单商品数量
            "ownSpec": item.ownSpec, //商品规格对象
            "skuId": item.skuId, //详情表中skuId
            "useCoupons": "0",
            "spuId": item.spuId
          })
        }
      })

      param.actualPay = param.actualPay + money
      param.totalPay = param.totalPay + money
      if (this.data.isActivity) {
        param.totalPay = this.data.actualPay * 100
        param.actualPay = this.data.actualPay * 100
      }

      param.memberPay = this.data.member * 100
      param.stordsPay = this.data.cards * 100

      // this.setData({
      //   actualPay: param.actualPay / 100
      // })
     

      param.couponId = couponObj ? couponObj.id : ''
      param.freightMoney = money
      param.postFee = money
      param.orderType = 0
      param.url = list[0].url || ''
      callback && callback(param)
    })


  },
  smOrder(list, callback, freightCb) {
    let param = {
      "totalPay": 0, //总金额，单位为分
      wechatPay: 0, //微信支付
      memberPay: 0, //会员卡支付
      stordsPay: 0, //储蓄卡支付
      "actualPay": 0, //实付金额。单位:分。如:20007，表示:200元7分
      "freightMoney": 0, //运费金额
      "paymentType": "1", //支付类型，1、在线支付，2、货到付款
      "postFee": "0", //邮费。单位:分。如:20007，表示:200元7分
      "customerId": wx.getStorageSync("userInfo").id, //客户id
      "buyerNick": wx.getStorageSync("userInfo").wechatNick, //买家昵称
      "buyerMessage": this.data.remark, //买家留言
      "receiverState": this.data.currentAddress.provinceName || "", //收获地址（省）
      "receiverCity": this.data.currentAddress.cityName || "", //收获地址（市）
      "receiverDistrict": this.data.currentAddress.areaName || "", //收获地址（区/县
      "receiverAddress": this.data.currentAddress.receiptAddress || "", //收获地址（街道、住址等详细地址）
      "receiverMobile": this.data.currentAddress.receiptMobile, //收货人手机
      "receiverZip": "", //收货人邮编
      "receiver": this.data.currentAddress.receiptName, //收货人name
      "invoiceType": "0", //发票类型(0无发票1普通发票，2电子发票，3增值税发票)
      "sourceType": "1", //订单来源：1:微信端 
      "isOffline": "0", //是否为线下 0否 1是
      "storeId": "", //线下门店标识
      "orderdetailList": [],
      "orderType": '',
      "companyName": '',
      "url": '',
      "activity": this.data.activity, //1秒杀活动，2拼团活动3.打包
      "promotiomIds": this.data.promotiomIds, //活动标识 秒杀活动 拼团活动的ID
      "timelyDelivery": this.data.timelyDelivery,
      "sendstartTime": this.data.sendstartTime,
      "sendendTime": this.data.sendendTime,
      "storeId": this.data.currentStore.storeId
    }
    if (list.length == 0) {
      freightCb && freightCb(0)
      callback && callback(null);
      return;
    }
    param.memberPay = this.data.member * 100
    param.stordsPay = this.data.cards * 100
    param.wechatPay = this.data.actualPay * 100

    this.getCarriage(list, (money) => {

      freightCb && freightCb(money);
      //不同url 商盟 下不同的订单
      let urls = []
      list.forEach(item => {
        urls.push(item.url)
      })
      urls = [...new Set(urls)]
      let urlObj = {}
      urls.forEach((url, index) => {
        urlObj[url] = []
      })
      list.forEach(item => {
        urlObj[item.url].push(item)
      })
      let tempList = []
      for (const url in urlObj) {
        let array = urlObj[url]
        array.forEach(item => {
          param.totalPay += item.price * item.num
          param.actualPay += item.price * item.num
          param.orderdetailList.push({
            "title": item.title, //商品名称
            "price": item.price, //商品价格
            "num": item.num, //订单商品数量
            "ownSpec": item.ownSpec, //商品规格对象
            "skuId": item.skuId, //详情表中skuId
            "spuId": item.spuId
          })
        })
        param.actualPay = param.actualPay + money
        param.totalPay = param.totalPay + money
        //这块是计算价钱吧
        // this.setData({
        //   actualPay: param.actualPay / 100
        // })

     

        param.freightMoney = money
        param.postFee = money
        param.orderType = 1
        param.url = url || ''
        tempList.push(param)
      }
      callback && callback(tempList)
    })
  },
  toPay(paramList, callback) {
    service.commitOrderMul(paramList, (res) => {
      callback(res)
    })
  },

  onShow: function () {

    if (!wx.getStorageSync('currentAddress')) {
      service.getdefaultAddress(wx.getStorageSync("userInfo").id, (res) => {
        let address = res.data[0] || {}
        if (res.data[0]) {
          wx.setStorageSync('currentAddress', address)
        }
        this.setData({
          currentAddress: res.data[0] || {},
          showaddbtn: res.data[0] ? false : true,
        });
        this.computedFreight()
      });

    } else {
      this.setData({
        currentAddress: wx.getStorageSync('currentAddress'),
        showaddbtn: false
      })
      this.computedFreight()
      wx.removeStorageSync('currentAddress')
    }


  },
  getCarriage(list, callback) {
    let provinceId = this.data.currentAddress.provinceId
    if (list.length == 0) callback(0);
    let tempList = []
    let spuIds = []
    list && list.forEach(item => {
      spuIds.push(item.spuId)
    })
    spuIds = [...new Set(spuIds)]
    let temObj = {}
    spuIds.forEach(id => {
      temObj[id] = []
    })

    list && list.forEach(item => {
      temObj[item.spuId].push(item)
    })
    for (const spuId in temObj) {
      let list = temObj[spuId]
      let param = {
        spuId: spuId,
        spuNum: 0,
        freightMoney: 0,
        areaId: provinceId
      }
      list.forEach(item => {
        param.spuNum += item.num
        param.freightMoney += item.num * Number(item.price)
      })
      tempList.push(param)
    }
    activityService.getOrderFreight(tempList, res => {
      callback && callback(res.data)
    })
  },
});